rm(list = ls())

# Set Working Directory to Replication Folder
taskdir 		<- "~/Dropbox/final_hai_perlman_replication/"
inputdir 		<- paste0(taskdir, "input/processing/regressions_survey2/")


setwd(taskdir)
library(tidyverse)
library(lfe)
require(data.table)
library(stringi)
library(gtable)
library(gridExtra)
library(grid)
library(lattice)


# Define all DVs
dvs <- c('tax_support' ,'politician_prevent' ,'politician_understand' ,
		'politician_advocate' ,'politician_sympathy'
		,'responsibility_local' ,'responsibility_federal' ,
		'responsibility_international',
		'climatetax_support', 'wildfire_morecommon',
		'carbon_footprint_score')




# Main Results - big plot with three dvs
load(paste0(inputdir, 'ols_survey2_controls.RData'))
toplot <- tibble(dv = NA, subset = NA, beta = NA, se = NA)
for (dv in dvs) {
	temp_regressions <- outlist[[dv]]
	mod1 <- temp_regressions[[1]]
	mod2 <- temp_regressions[[2]]
	mod3 <- temp_regressions[[3]]
	mod4 <- temp_regressions[[4]]
	mod5 <- temp_regressions[[5]]
	mod6 <- temp_regressions[[6]]
	mod7 <- temp_regressions[[7]]
	mod8 <- temp_regressions[[8]]
	temp <- tibble(dv = dv, 
				   subset = rep(c('All', 'Republicans', 'Democrats', 'Independents'),2),
				   politician = c(rep('Republican',4),rep('Democrat',4)),
				   beta = c(mod1$coef[1], mod2$coef[1], mod3$coef[1],mod4$coef[1],
				   			mod5$coef[1], mod6$coef[1], mod7$coef[1],mod8$coef[1]),
				   se = c(mod1$rse[1], mod2$rse[1], mod3$rse[1],mod4$rse[1],
				   		  mod5$rse[1], mod6$rse[1], mod7$rse[1],mod8$rse[1])
				   )
	toplot <- bind_rows(toplot, temp)
}
toplot <-toplot%>%filter(!is.na(dv))%>%
				mutate(up = beta + 1.96*se,
					   down = beta-1.96*se,
					   up90 = beta + 1.64*se,
					   down90 = beta - 1.64*se)



# write in DV names
toplot<- toplot %>% mutate(
						question = case_when(
							dv =="politician_understand" ~ "has a good understanding of wildfires and their causes?",
							dv =="politician_sympathy" ~ "How sympathetic or unsympathetic did the politician seem towards those impacted?",
							dv =="politician_prevent" ~ "will work to prevent future wildfires?",
							dv =="politician_advocate" ~ "will be an effective advocate for federal disaster relief?",
							dv =="responsibility_international" ~ "The international community",
							dv =="responsibility_federal" ~ "The federal government",
							dv =="responsibility_local" ~ "Local/state government",
							dv =="tax_support" ~ "How likely would you be to support this new tax?",
							dv =="climatetax_support" ~ "How likely would you be to support this new climate tax?",
							dv =="wildfire_morecommon" ~ "Are wildfires going to become more common?",
							dv =="carbon_footprint_score" ~ "Overall Carbon Footprint Score",
							TRUE ~ as.character(NA)
						)
)
question_levels <- c("has a good understanding of wildfires and their causes?",
								   "will work to prevent future wildfires?",
								   "will be an effective advocate for federal disaster relief?",
								   "How sympathetic or unsympathetic did the politician seem towards those impacted?",
								   "How likely would you be to support this new tax?",
								   "How likely would you be to support this new climate tax?",
								   "Are wildfires going to become more common?",
								   "Overall Carbon Footprint Score",
								   "Local/state government",
								   "The federal government",
								   "The international community")

toplot$question <- factor(toplot$question,
						levels = question_levels)

# get party variable in correct order
toplot$subset<- factor(toplot$subset,
											levels = c("Independents","Democrats",
																"Republicans","All"))

# rename variables
toplot<- toplot%>%mutate(politician = case_when(
							politician=="Republican" ~ "Republican Politician",
							politician=="Democrat" ~ "Democratic Politician",
							TRUE ~ as.character(NA)
						))%>%
					rename(Respondent = subset)

# Plot!
c('tax_support' ,'politician_prevent' ,'politician_understand' ,
		'politician_advocate' ,'politician_sympathy'
		,'responsibility_local' ,'responsibility_federal' ,
		'responsibility_international',
		'climatetax_support', 'wildfire_morecommon',
		'carbon_footprint_score')
# Separate plots for each question, except for 
#	politician_understand,'politician_prevent', politician_advocate 
#	so they can be stacked

# first batch
plotlist	<- list() 
for (d in dvs) {
	df<- toplot%>%filter(dv == d)
	qs <- df$question[1]
	p1<- ggplot(df)+
		geom_vline(xintercept = 0, linetype = 'dashed')+
		geom_linerange(aes(y = Respondent, xmax = up90, xmin = down90,
									color = Respondent,
									linetype = "90% CI"), 
									size = 0.6, width = 0.2)+
		geom_linerange(aes(y = Respondent, xmax = up, xmin = down,
									color = Respondent,
									linetype = "95% CI"), 
									size = 0.6, width = 0.2)+
		scale_linetype_manual(name = 'CI',
							  values = c('solid','dotted'))+
		geom_point(aes(y = Respondent, x = beta,
									color = Respondent), size = 2)+
		geom_text(aes(y = Respondent, x = beta,
													color = Respondent, label = round(beta,2) ),
													size = 3,
												nudge_y = 0.3)+
		theme_bw()+
		facet_grid(cols = vars(politician), switch='y')+
		scale_color_manual(values = list('All' = 'black',
																		'Democrats' = 'steelblue3',
																	  'Independents' = 'grey60',
																	  'Republicans' = 'tomato3'))+
		ggtitle(qs)+
		xlab('Treatment Effect')+
		theme(title =element_text(size=6, face='bold'))
	plotlist[[d]] <- p1
	# p1

}
for (d in c('tax_support' ,
			'politician_sympathy'
			,'responsibility_local' ,'responsibility_federal' ,
			'responsibility_international',
			'climatetax_support', 'wildfire_morecommon',
			'carbon_footprint_score')) {
ggsave(paste0(taskdir, 'output/regression_plots/ols_survey2_controls/survey2_results',d,'.png'),
				plotlist[[d]],
				width = 7,
				height = 2.66,
				dpi = 600)
}

# second batch
get_legend<-function(myggplot){
  tmp <- ggplot_gtable(ggplot_build(myggplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}
legend <- get_legend(plotlist[['politician_prevent']])




mainplot<- grid.arrange(arrangeGrob(
				plotlist[['politician_understand']]+
						theme(legend.position="none")+
						xlim(c(-0.29,0.25)), 
			 	plotlist[['politician_prevent']]+
			 			theme(legend.position="none")+
						xlim(c(-0.29,0.25)),
			 	plotlist[['politician_advocate']]+
			 			theme(legend.position="none")+
						xlim(c(-0.29,0.25))
			 	),
			 legend ,
			ncol = 2,
			widths = c(2.5,1),
			top = "How confident are you that the politician:")

ggsave(paste0(taskdir, 'output/regression_plots/ols_survey2_controls/survey2_results_main.png'),
				mainplot,
				width = 7,
				height = 7,
				dpi = 600)



# create plot of belief in wildfire frequency, pooling 
# both types of politicians
load(paste0(inputdir, 'ols_survey2_pooled_wildfiremorecommon.RData'))
toplot <- tibble(dv = NA, subset = NA, beta = NA, se = NA)
for (dv in "wildfire_morecommon") {
	temp_regressions <- outlist[[dv]]
	mod1 <- temp_regressions[[1]]
	mod2 <- temp_regressions[[2]]
	mod3 <- temp_regressions[[3]]
	mod4 <- temp_regressions[[4]]

	temp <- tibble(dv = dv, 
				   subset = rep(c('All', 'Republicans', 'Democrats', 'Independents'),1),
				   politician = c(rep('Republican',2),rep('Democrat',2)),
				   beta = c(mod1$coef[1], mod2$coef[1], mod3$coef[1],mod4$coef[1]),
				   se = c(mod1$rse[1], mod2$rse[1], mod3$rse[1],mod4$rse[1])
				   )
	toplot <- bind_rows(toplot, temp)
}
toplot <-toplot%>%filter(!is.na(dv))%>%
				mutate(up = beta + 1.96*se,
					   down = beta-1.96*se,
					   up90 = beta + 1.64*se,
					   down90 = beta - 1.64*se)

# get party variable in correct order
toplot$subset<- factor(toplot$subset,
											levels = c("Independents","Democrats",
																"Republicans","All"))
q1<- ggplot(toplot %>% filter(dv %in% c('wildfire_morecommon')) )+
	geom_vline(xintercept = 0, linetype = 'dashed')+
	geom_linerange(aes(y = subset, xmax = up90, xmin = down90,
								color = subset,
								linetype = "90% CI"), 
								size = 0.6, width = 0.2)+
	geom_linerange(aes(y = subset, xmax = up, xmin = down,
								color = subset,
								linetype = "95% CI"), 
								size = 0.6, width = 0.2)+
	scale_linetype_manual(name = 'CI',
						  values = c('solid','dotted'))+
	geom_point(aes(y = subset, x = beta,
								color = subset), size = 2)+
	geom_text(aes(y = subset, x = beta,
												color = subset, label = round(beta,2) ),
												size = 3,
											nudge_y = 0.3)+
	theme_bw()+
	scale_color_manual(values = list('All' = 'black',
																	'Democrats' = 'steelblue3',
																  'Independents' = 'grey60',
																  'Republicans' = 'tomato3'))+
	ggtitle("Are wildfires going to become more common?")+
	xlab('Treatment Effect')
q1
ggsave(paste0(taskdir, 'output/regression_plots/ols_survey2_controls/survey2_resultswildfire_morecommon_pooled.png'),
				q1,
				width = 5,
				height = 2.66,
				dpi = 600)

































